package controllers

import (
	"com.wangzhumo.lottery/conf"
	"com.wangzhumo.lottery/models"
	"com.wangzhumo.lottery/utils"
	"fmt"
	"log"
	"strconv"
	"time"
)

// 内部方法
// 检测是用户是否达到了今日次数限制
func (c *IndexController) checkUserDay(uid int, count int64) bool {
	userToday := c.UserDayService.GetUserToday(uid)
	// 获取到数据
	if userToday != nil && uid == userToday.Uid {
		if userToday.Num >= conf.UserPrizeMax {
			// 如果大于最大次数，就不能够再参加了
			if int(count) < userToday.Num {
				utils.InitUserLuckyNum(uid, userToday.Num)
			}
			return false
		} else {
			// 否则自增
			userToday.Num++
			if int(count) < userToday.Num {
				utils.InitUserLuckyNum(uid, userToday.Num)
			}
			err := c.UserDayService.Update(userToday, nil)
			if err != nil {
				log.Println("UserDayService update err", err)
			}
		}
	} else {
		// 没有，需要添加进来
		year, month, day := time.Now().Date()
		dateStr := fmt.Sprintf("%d%02d%02d", year, month, day)
		autoit, _ := strconv.Atoi(dateStr)
		userDay := &models.CountRecord{
			Uid:        uid,
			Day:        autoit,
			Num:        1,
			SysCreated: int(time.Now().Unix()),
		}
		// 写入mysql
		err := c.UserDayService.Insert(userDay)
		if err != nil {
			log.Println("insert userday record error", err)
		}
		// 写入redis
		utils.InitUserLuckyNum(uid, 1)
	}

	return true
}
